<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @example 三種情況
 *
 */

class Model_Fill extends Model_Database {
	public function to($dataset, $search_fields)
	{
		foreach ($search_fields as $key => $value)
		{
			$model = '';
			$fill_fields = array();
			switch ($key) {
				case 'uid':
					$model = 'member';
					$fill_fields = array('username','nickname','phone','sex');
					break;
				case 'gid':
					$model = 'group';
					$fill_fields = array('group_name');
					break;
				
			}
			if (empty($model))
				continue;
			$array = search_fields($dataset, $value);
			if (empty($array))
				continue;
			$result = Model::instance($model)->search(array($key => $array));
			$this->_rev_fill($dataset, $result['data'], $value, $fill_fields);

		}
		return $dataset;
	}

	private function _rev_fill(&$dataset, &$data, &$keys, &$fields)
	{
		$keys = _array_selector_subkey($keys);
		foreach ($dataset as $key => $value) 
		{
			if (is_array($value))
				$this->_rev_fill($dataset[$key], $data, $keys, $fields);
			else
			{
				if (in_array($key, $keys) && array_key_exists($value, $data)) //$KEY存在,並且在$data中也存在
				{
					foreach ($fields as $field) {
						$dataset[$key.'_'.$field] = $data[$value][$field];
					}
				}
			}
		}
	}
}